package com.krause.marinechart.iso8211;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;

import android.os.AsyncTask;
import android.util.Log;
import android.widget.ProgressBar;
import android.widget.TextView;


public class Module extends AsyncTask<File, Integer, Void> implements Constants {
	
	private ProgressBar mProgressBar;
	private TextView mTv;
	
	private BufferedInputStream ddfFile;
	private DDRecord mDDR;
	private ArrayList<Record> mDRs;
	
	protected static StringBuffer sb = new StringBuffer();
	
	public Module(ProgressBar progress, TextView tv)	{
		mProgressBar = progress;
		mTv = tv;
		sb = new StringBuffer();
	}
	
	protected void readFile() {
		try {
			mDDR = new DDRecord(ddfFile);
			ddfFile.mark(1);
			
			mDRs = new ArrayList<Record>();
			int i = mDDR.mLeader.recLength;
			while (ddfFile.read() >= 0) {
				if(isCancelled()) break;
				ddfFile.reset();
				Record mRecord = new Record(ddfFile);
				i += mRecord.mLeader.recLength;
				mDRs.add(mRecord);
				ddfFile.mark(1);
				publishProgress(i);
			}
			Log.d("DONE", i + " bytes read");
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	protected Void doInBackground(File... files) {
			try {
				try {
					ddfFile = new BufferedInputStream(new FileInputStream(files[0]));
					readFile();
				} finally {
					ddfFile.close();
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
	}
	
	@Override
	protected void onProgressUpdate(Integer... progress) {
		mProgressBar.setProgress(progress[0]);
		mTv.append(new String(Module.sb));
		sb = new StringBuffer();
	}
	
	public static int getRecordCount(File file) {
		try {
			int i = 0;
			final int FIELD_LENGTH = 5;
			final BufferedInputStream bufIS = new BufferedInputStream(new FileInputStream(file));
			byte[] recLength = new byte[5];
			while (bufIS.read(recLength, 0, FIELD_LENGTH) >= 0) {
				int temp = Integer.parseInt(new String(recLength, 0, FIELD_LENGTH));
				bufIS.skip(temp - FIELD_LENGTH);
				i++;
			}
			
			return i;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return -1;
	}


}
